package com.itdct.onflow.system.common.manager

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner
import com.itdct.onflow.core.extend.logInfo
import com.itdct.onflow.core.util.TimeUtil
import com.itdct.onflow.system.common.base.BaseManager
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.ExecutorService

/**
 * @author Zhouwx
 * @date 2025/9/22 10:43:48
 * @version 1.0
 * @description
 */
@Component
class CleanLogicDeleteManager(
    @Value("\${spring.datasource.url}")
    val url: String,
    @Qualifier("virtualThreadPoolExecutor")
    val virtualThreadPoolExecutor: ExecutorService
) : BaseManager() {
    fun cleanDelData() {
        logInfo("url is $url")
        var tempStr = url
        if (url.contains("?")) {
            // INFO: Zhouwx: 2025/4/25 说明后面有参数配置
            tempStr = url.substring(0, url.indexOf("?"))
        }
        val dbName = tempStr.substring(tempStr.lastIndexOf("/") + 1)

        val logicDeleteConfig = onflowConfig.logicDelete
        val defaultCleanTime = logicDeleteConfig.defaultCleanTime
        val defaultLogicDeleteCleanTime = defaultCleanTime
        val logicDeleteField = logicDeleteConfig.logicDeleteField
        val tableCleanConfigs = logicDeleteConfig.tableCleanConfigs

        val selectList = SqlRunner.db().selectList(
            "SELECT TABLE_NAME\n" +
                    "FROM INFORMATION_SCHEMA.COLUMNS\n" +
                    "WHERE TABLE_SCHEMA = '${dbName}'\n" +
                    "  AND COLUMN_NAME IN ('${logicDeleteField}', 'delete_time')\n" +
                    "GROUP BY TABLE_NAME\n" +
                    "HAVING COUNT(DISTINCT COLUMN_NAME) = 2;"
        )

        for (tableName in selectList.map { it["TABLE_NAME"] as String }) {
            virtualThreadPoolExecutor.submit {
                var cleanDay = defaultLogicDeleteCleanTime
                tableCleanConfigs?.also {
                    it[tableName]?.also {
                        cleanDay = it
                    }
                }
                val calendar = Calendar.getInstance()
                calendar.add(Calendar.DAY_OF_YEAR, -cleanDay)
                val time = calendar.time
                val timeString = TimeUtil.dateToTimeString(time, "yyyy-MM-dd HH:mm:ss")
                val countSql = "select count(0) as c from $tableName where ${logicDeleteField} > 0 and delete_time < '${timeString}'"
                val count = SqlRunner.db().selectOne(countSql)["c"] as Long
                logInfo("delete count is $count in table $tableName")
                if (count == 0L) {
                    return@submit
                }
                val deleteCache = "delete from $tableName where ${logicDeleteField} > 0 and delete_time < '${timeString}'"
                SqlRunner.db().delete(deleteCache)
            }
        }
    }
}